package com.jt.service.impl;

import com.jt.service.FileService;
import com.jt.vo.ImageVO;
import net.sf.jsqlparser.statement.create.table.Index;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.lang.management.BufferPoolMXBean;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;


@Service
@PropertySource("classpath:/properties/image.properties")
public class FileServiceImpl implements FileService {
    private static Set<String> imageTypeSet = new HashSet<>();

    @Value("${image.localDirPath}")
    private String localDirPath;
    @Value("${image.urlPath}")
    private String urlPath;

    static {
        imageTypeSet.add(".jpg");
        imageTypeSet.add(".png");
        imageTypeSet.add(".gif");
    }

    @Override
    public ImageVO upload(MultipartFile uploadFile) {
        String fileName = uploadFile.getOriginalFilename();
        fileName = fileName.toLowerCase();
        int index = fileName.lastIndexOf(".");
        String fileType = fileName.substring(index);
        if (!imageTypeSet.contains(fileName)) {
            return ImageVO.fail();
        }
        try {
            BufferedImage bufferedImage = ImageIO.read(uploadFile.getInputStream());
            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();
            if (width == 0 || height == 0) {
                return ImageVO.fail();
            }
        } catch (IOException e) {
            e.printStackTrace();
            return ImageVO.fail();
        }

        String datePath = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
        String localDir = localDirPath + datePath;

        File dirFile = new File(localDir);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        String uuid = UUID.randomUUID().toString().replace("-", "");
        String uuidFileName = uuid + fileType;

        String realFilePath = localDir + uuidFileName;
        File imageFile = new File(realFilePath);

        try {
            uploadFile.transferTo(imageFile);
        } catch (IOException e) {
            e.printStackTrace();
            return ImageVO.fail();
        }

        String url = urlPath + datePath + uuidFileName;
        return ImageVO.success(url);
    }

}
